/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.infodb.lock.config;

import com.alibaba.fastjson.JSONObject;
import com.hyts.infodb.lock.bean.RedissonSingleBean;
import com.hyts.infodb.lock.template.DistributeLockTemplate;
import com.hyts.infodb.lock.template.SingleDistributeLockTemplate;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @project-name:infodb
 * @package-name:com.hyts.infodb.lock.config
 * @author:LiBo/Alex
 * @create-date:2020-03-01 21:14
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description: 分布式锁操作得服务功能实现
 */
@Slf4j
@EnableConfigurationProperties
@Configuration
public class DistributeLockConfiguration {


    @Autowired
    RedissonSingleBean redissonSingleBean;


    /**
     * 设置关闭方法以及定义构造对象服务
     * RedissonClient对象信息
     * @return
     * @throws IOException
     */
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient(){
        Config config = null;
        try {
            config = Config.fromJSON(JSONObject.toJSONString(redissonSingleBean));
            return Redisson.create(config);
        } catch (IOException e) {
            log.error("初始化RedissonClient客户端失败!",e);
            return null;
        }
    }

    /**
     * 分布式锁模板功能实现操作对象
     * @param redissonClient
     * @return
     */
    @Bean
    DistributeLockTemplate distributedLockTemplate(RedissonClient redissonClient) {
        return new SingleDistributeLockTemplate(redissonClient);
    }
}
